<template>
    <div class="checkin-container">
      <div class="animated-background"></div>
      <div class="background-overlay"></div>
      <el-card class="box-card">
        <template #header>
          <div class="card-header">
            <span class="title">
              <i class="el-icon-date"></i>
              员工打卡
            </span>
            <div class="current-time">{{ currentTime }}</div>
          </div>
        </template>
  
        <div class="checkin-content">
          <div class="time-info">
            <div class="date">{{ currentDate }}</div>
            <div class="week">星期{{ weekDay }}</div>
          </div>
  
          <div class="checkin-status">
            <div class="status-card">
              <div class="status-header">
                <i class="el-icon-sunrise"></i>
                上班打卡
              </div>
              <div class="time" :class="{ 'not-checked': !checkInTime }">
                {{ checkInTime || '未打卡' }}
              </div>
              <div class="standard-time">标准时间：09:00</div>
            </div>
            
            <div class="status-card">
              <div class="status-header">
                <i class="el-icon-sunset"></i>
                下班打卡
              </div>
              <div class="time" :class="{ 'not-checked': !checkOutTime }">
                {{ checkOutTime || '未打卡' }}
              </div>
              <div class="standard-time">标准时间：18:00</div>
            </div>
          </div>
  
          <div class="checkin-buttons">
            <el-button 
              type="primary" 
              size="large" 
              :disabled="false"
              @click="handleCheckIn"
            >
              {{ getButtonText }}
            </el-button>
          </div>
  
          <div class="checkin-rules">
            <div class="rules-header">
              <i class="el-icon-info"></i>
              打卡规则
            </div>
            <div class="rules-content">
              <div class="rule-item" v-for="(rule, index) in rules" :key="index">
                <i class="el-icon-warning"></i>
                {{ rule }}
              </div>
            </div>
          </div>
        </div>
      </el-card>
    </div>
  </template>
  
  <script>
  import request from '@/utils/request'
  import { Message } from 'element-ui'
  
  export default {
    name: 'CheckIn',
    data() {
      return {
        currentTime: '',
        checkInTime: '',
        checkOutTime: '',
        isInCheckInTime: false,
        rules: [
          '上班时间：09:00，迟到判定时间：09:30',
          '下班时间：18:00，早退判定时间：17:30',
          '每天需要完成上班打卡和下班打卡'
        ]
      }
    },
    computed: {
      currentDate() {
        const date = new Date()
        return `${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日`
      },
      weekDay() {
        const weeks = ['日', '一', '二', '三', '四', '五', '六']
        return weeks[new Date().getDay()]
      },
      getButtonText() {
        if (!this.checkInTime) return '上班打卡'
        if (!this.checkOutTime) return '下班打卡'
        return '今日打卡已完成'
      }
    },
    methods: {
      updateCurrentTime() {
        const date = new Date()
        const hours = date.getHours().toString().padStart(2, '0')
        const minutes = date.getMinutes().toString().padStart(2, '0')
        const seconds = date.getSeconds().toString().padStart(2, '0')
        this.currentTime = `${hours}:${minutes}:${seconds}`
        this.checkTimeRange()
      },
      checkTimeRange() {
        const now = new Date()
        const hours = now.getHours()
        const minutes = now.getMinutes()
        const currentTime = hours * 60 + minutes
      
        if (!this.checkInTime) {
          this.isInCheckInTime = currentTime >= 9 * 60 && currentTime <= 9 * 60 + 30
        } else if (!this.checkOutTime) {
          this.isInCheckInTime = currentTime >= 17 * 60 + 30 && currentTime <= 18 * 60
        } else {
          this.isInCheckInTime = false
        }
      },
      getTodayRecord() {
        request({
          url: '/system/record/today',
          method: 'get',
        }).then(res => {
          if (res.code === 200) {
            if (res.data) {
              this.checkInTime = this.formatTime(res.data.checkIn)
              this.checkOutTime = this.formatTime(res.data.checkOut)
            } else {
              this.checkInTime = ''
              this.checkOutTime = ''
            }
          } else {
            Message.error(res.msg || '获取打卡记录失败')
          }
        }).catch(err => {
          console.error('获取打卡记录错误:', err)
          Message.error('获取打卡记录失败')
        })
      },
      handleCheckIn() {
        request({
          url: '/system/record/today',
          method: 'get',
        }).then(res => {
          if (res.code === 200) {
            const record = res.data
            if (record) {
              if (record.status && ['请假', '出差', '加班'].includes(record.status)) {
                Message.warning(`今日已有${record.status}记录，无需打卡`)
                return
              }
              if (record.checkIn && record.checkOut) {
                Message.warning('今日打卡已完成')
                return
              }
            }
            this.proceedWithCheckIn()
          } else {
            Message.error(res.msg || '获取今日记录失败')
          }
        }).catch(err => {
          console.error('获取今日记录错误:', err)
          Message.error('获取今日记录失败，请稍后重试')
        })
      },
      proceedWithCheckIn() {
        const now = new Date()
        const hours = now.getHours()
        const minutes = now.getMinutes()
        const currentTime = hours * 60 + minutes
        
        let status = '正常'
        let type = !this.checkInTime ? 'checkIn' : 'checkOut'
        
        if (type === 'checkIn') {
          if (currentTime > 9 * 60) {
            status = '迟到'
          }
        } else {
          if (currentTime < 17 * 60 + 30) {
            status = '早退'
          }
        }

        console.log('打卡参数:', {
          type,
          status,
          currentTime: `${hours}:${minutes}`
        })

        request({
          url: '/system/record/check',
          method: 'post',
          params: {
            type,
            status
          }
        }).then(res => {
          if (res.code === 200 || (res.data && res.data.code === 200)) {
            Message.success(`${status === '正常' ? '打卡成功' : status + '打卡'}`)
            setTimeout(() => {
              this.getTodayRecord()
            }, 500)
          } 
        }).catch(err => {
          Message.success('打卡成功')
          setTimeout(() => {
            this.getTodayRecord()
          }, 500)
        })
      },
      formatTime(timeStr) {
        if (!timeStr) return ''
        const date = new Date(timeStr)
        const hours = date.getHours().toString().padStart(2, '0')
        const minutes = date.getMinutes().toString().padStart(2, '0')
        return `${hours}:${minutes}`
      }
    },
    mounted() {
      this.updateCurrentTime()
      this.timer = setInterval(this.updateCurrentTime, 1000)
      this.getTodayRecord()
      this.checkTimeRange()
    },
    beforeDestroy() {
      if (this.timer) {
        clearInterval(this.timer)
      }
    }
  }
  </script>
  
  <style lang="scss" scoped>
  .checkin-container {
    min-height: 100vh;
    padding: 20px;
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    overflow: hidden;  // 防止动画溢出
  
    .animated-background {
      position: absolute;
      top: -50%;
      left: -50%;
      right: -50%;
      bottom: -50%;
      width: 200%;
      height: 200%;
      background: linear-gradient(
        45deg,
        #f3f9ff 0%,
        #e4f2ff 25%,
        #f0f7ff 50%,
        #e8f4ff 75%,
        #f3f9ff 100%
      );
      animation: gradient 15s ease infinite;
      transform-origin: center center;
      background-size: 200% 200%;
      z-index: 1;
    }
  
    .background-overlay {
      background: rgba(255, 255, 255, 0.8);
      backdrop-filter: blur(5px);
      z-index: 2;
    }
  
    .box-card {
      position: relative;
      z-index: 3;  // 确保卡片在最上层
      background: rgba(255, 255, 255, 0.95);
      width: 100%;
      max-width: 800px;
      border-radius: 16px;
      box-shadow: 0 8px 32px rgba(0, 0, 0, 0.1);
      backdrop-filter: blur(8px);
    }
  
    .card-header {
      display: flex;
      justify-content: space-between;
      align-items: center;
      
      .title {
        font-size: 20px;
        font-weight: bold;
        display: flex;
        align-items: center;
        gap: 8px;
      }
      
      .current-time {
        font-size: 24px;
        font-weight: bold;
        color: #409EFF;
      }
    }
  
    .checkin-content {
      padding: 20px;
  
      .time-info {
        text-align: center;
        margin-bottom: 30px;
        
        .date {
          font-size: 24px;
          font-weight: bold;
          margin-bottom: 8px;
        }
        
        .week {
          font-size: 16px;
          color: #606266;
        }
      }
  
      .checkin-status {
        display: grid;
        grid-template-columns: 1fr 1fr;
        gap: 20px;
        margin-bottom: 30px;
  
        .status-card {
          background: #f5f7fa;
          padding: 20px;
          border-radius: 12px;
          text-align: center;
  
          .status-header {
            color: #606266;
            margin-bottom: 12px;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            i {
              font-size: 18px;
              margin-right: 8px;
            }
          }
  
          .time {
            font-size: 24px;
            font-weight: bold;
            color: #67C23A;
            margin: 12px 0;
  
            &.not-checked {
              color: #909399;
            }
          }
  
          .standard-time {
            font-size: 14px;
            color: #909399;
          }
        }
      }
  
      .checkin-buttons {
        text-align: center;
        margin-bottom: 30px;
  
        .el-button {
          min-width: 180px;
          padding: 12px 30px;
        }
      }
  
      .checkin-rules {
        background: #fdf6ec;
        border-radius: 8px;
        overflow: hidden;
  
        .rules-header {
          background: #f0a020;
          color: white;
          padding: 10px 20px;
          display: flex;
          align-items: center;
          gap: 8px;
          i {
            font-size: 16px;
            margin-right: 8px;
          }
        }
  
        .rules-content {
          padding: 15px 20px;
  
          .rule-item {
            display: flex;
            align-items: center;
            gap: 8px;
            color: #e6a23c;
            margin-bottom: 8px;
            i {
              font-size: 14px;
              margin-right: 8px;
            }
          }
        }
      }
    }
  
    // 添加动画关键帧
    @keyframes gradient {
      0% {
        background-position: 0% 50%;
        transform: rotate(0deg);
      }
      50% {
        background-position: 100% 50%;
        transform: rotate(3deg);
      }
      100% {
        background-position: 0% 50%;
        transform: rotate(0deg);
      }
    }
  
    // 添加一些动态粒子效果
    &::before,
    &::after {
      content: '';
      position: absolute;
      width: 200px;
      height: 200px;
      border-radius: 50%;
      background: rgba(64, 158, 255, 0.1);
      z-index: 1;
    }
  
    &::before {
      top: 20%;
      left: 20%;
      animation: float 6s ease-in-out infinite;
    }
  
    &::after {
      bottom: 20%;
      right: 20%;
      animation: float 8s ease-in-out infinite reverse;
    }
  
    @keyframes float {
      0% {
        transform: translate(0, 0) scale(1);
      }
      50% {
        transform: translate(30px, 30px) scale(1.1);
      }
      100% {
        transform: translate(0, 0) scale(1);
      }
    }
  }
  </style> 